from typing import List, Dict
from ..repository.chatMessagesFlow_repository import chat_message_flow_repo
from ..repository.chatMessages_repository import chat_message_repo


# ==============================
# 全局变量：对话历史存储
# ==============================
# 使用嵌套字典结构，便于扩展不同会话和模型
_chat_histories: Dict[int, List[Dict[str, str]]] = {}


# ==============================
# 辅助函数
# ==============================
def build_message_history(
    session_id: int,
    system_prompt: str,
    user_input: str,
    enable_memory: bool,
    history_limit: int = 20
) -> List[Dict[str, str]]:
    """构建消息历史"""
    if enable_memory:
        # 历史中无会话id则初始化
        if session_id not in _chat_histories:
            # 根据会话id查询数据库中会话聊天历史
            message_list = chat_message_repo.get_messages_by_session_id(session_id)
            # 如果信息列表不为空，则查询每条信息的文本流程
            if message_list:
                for message in message_list:
                    message_id = message['id']
                    # 查询该消息的文本流程，限制返回
                    flows = chat_message_flow_repo.get_message_flows_text_by_message_id(message_id, message_limit=history_limit)
                    for flow in reversed(flows):  # 倒序添加，保证时间顺序
                        role = "user" if flow['message_type'] == 'input_text' else "assistant"
                        content = flow['content']
                        append_to_history(session_id, role, content)
            else:
                #如果数据库中没有历史会话，则新建
                _chat_histories[session_id] = [{"role": "system", "content": system_prompt}]


        # 添加用户输入
        history = _chat_histories[session_id]
        history.append({"role": "user", "content": user_input})

        # 限制历史记录长度
        if len(history) > history_limit:
            history = history[-history_limit:]
        _chat_histories[session_id] = history
    else:
        history = [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_input},
        ]
    return history


def append_to_history(session_id: int, role: str, content: str):
    """向历史中添加消息"""
    if session_id not in _chat_histories:
        # 避免未初始化直接添加
        _chat_histories[session_id] = []
    _chat_histories[session_id].append({"role": role, "content": content})


# ==============================
# 对外 API：记忆管理
# ==============================

def clear_memory(session_id: int) -> None:
    """清空指定会话的记忆"""
    if session_id in _chat_histories:
        del _chat_histories[session_id]
        print(f"🗑️ 已清除会话 {session_id} 的记忆")


def get_history(session_id: int) -> List[Dict[str, str]]:
    """获取指定会话的历史记录"""
    return _chat_histories.get(session_id, [])


def clear_all_memories() -> None:
    """清空所有会话记忆"""
    _chat_histories.clear()
    print("🗑️ 已清除所有会话记忆")


def list_sessions() -> List[int]:
    """列出所有活跃会话"""
    return list(_chat_histories.keys())